/*
 * @Author: xiehangyun 
 * @Date: 2025-05-16 18:15:40 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2025-11-11 20:01:07
 */

import { makeAutoObservable } from "mobx";
import goodsTemlateApi from './goodsTemlateApi';
import { GoodsData } from "types/type";
import Taro from '@tarojs/taro';
import designerStore from '@/pages/Designer/designerStore';
import ttOrderApi from "@/api/ttOrderApi";

class GoodsTemlateStore {

    constructor() {
        makeAutoObservable(this, {}, { deep: false });
    }

    // 模板分类列表
    templateCategories: Array<{
        ifShow: boolean;
        productNegativeId: number;
        sort: number;
        templateId: number;
        templateName: string;
        designs: Array<{
            data: GoodsData["productData"];
            designId: number;
            ifShow: boolean;
            picUrls: string;
            sort: number;
            // 兼容可能的其他字段
            id?: number;
            picUrl?: string;
        }>
    }> = [];

    // 错误信息
    errorMsg = '';

    // API加载状态
    apiLoading = false;

    // 分页相关状态
    activeTabIndex = 0;
    page = 1;
    pageSize = 9; // 每页9个数据
    loadMoreLoading = false;
    hasMore = true;
    displayedDesigns: any[] = [];
    scrollTop = 0;
    productNegativeId = 0;

    // 根据底板ID获取模板列表
    async getTemplatesByNegativeId(productNegativeId: number) {
        this.apiLoading = true;
        this.errorMsg = '';
        this.productNegativeId = productNegativeId;

        try {
            const goodsTemlateData = await ttOrderApi.listByNegativeId(productNegativeId);
            this.templateCategories = goodsTemlateData || [];
            // 获取数据后自动重置分页
            if (this.templateCategories.length > 0) {
                this.resetPagination();
            }
            return this.templateCategories;
        } catch (error) {
            this.errorMsg = '获取模板列表失败，请稍后重试';
            console.error('获取模板列表失败:', error);
            return [];
        } finally {
            this.apiLoading = false;
        }
    }

    // 重置分页状态
    resetPagination() {
        this.page = 1;
        this.hasMore = true;
        this.displayedDesigns = [];
        this.loadInitialData();
    }

    // 加载初始数据
    loadInitialData() {
        // 添加防御性检查，确保visibleCategories存在且不为空
        if (!this.visibleCategories || this.visibleCategories.length === 0) {
            console.log('visibleCategories为空，无法加载初始数据');
            this.displayedDesigns = [];
            this.hasMore = false;
            return;
        }

        // 确保activeTabIndex有效
        if (this.activeTabIndex < 0 || this.activeTabIndex >= this.visibleCategories.length) {
            console.log('activeTabIndex超出范围:', this.activeTabIndex);
            this.displayedDesigns = [];
            this.hasMore = false;
            return;
        }

        const activeCategory = this.visibleCategories[this.activeTabIndex];
        if (!activeCategory || !activeCategory.designs || !Array.isArray(activeCategory.designs)) {
            this.displayedDesigns = [];
            this.hasMore = false;
            return;
        }

        const filteredDesigns = activeCategory.designs.filter(design => design.ifShow !== false);
        const initialData = filteredDesigns.slice(0, this.pageSize);

        this.displayedDesigns = initialData;
        this.hasMore = filteredDesigns.length > this.pageSize;
    }

    // 加载更多数据
    async loadMore() {
        console.log('加载更多数据');
        // 添加防御性检查，确保visibleCategories存在且不为空
        if (!this.visibleCategories || this.visibleCategories.length === 0) {
            console.log('visibleCategories为空，无法加载更多数据');
            return;
        }

        // 确保activeTabIndex有效
        if (this.activeTabIndex < 0 || this.activeTabIndex >= this.visibleCategories.length) {
            console.log('activeTabIndex超出范围:', this.activeTabIndex);
            return;
        }

        const activeCategory = this.visibleCategories[this.activeTabIndex];

        if (this.loadMoreLoading || !this.hasMore || !activeCategory || !activeCategory.designs || !Array.isArray(activeCategory.designs)) {
            return;
        }

        this.loadMoreLoading = true;

        try {
            // 模拟网络请求延迟
            await new Promise(resolve => setTimeout(resolve, 500));

            const filteredDesigns = activeCategory.designs.filter(design => design.ifShow !== false);
            const startIndex = this.page * this.pageSize;
            const endIndex = startIndex + this.pageSize;
            const newDesigns = filteredDesigns.slice(startIndex, endIndex);

            if (newDesigns.length > 0) {
                this.displayedDesigns = [...this.displayedDesigns, ...newDesigns];
                this.page += 1;
            } else {
                this.hasMore = false;
            }
        } catch (error) {
            console.error('加载更多数据失败:', error);
        } finally {
            this.loadMoreLoading = false;
        }
    }

    // 处理滚动事件
    handleScroll(e: any) {
        const { scrollTop, scrollHeight, clientHeight } = e.target;
        this.scrollTop = scrollTop;

        // 当滚动到距离底部100rpx时，触发加载更多
        if (scrollHeight - scrollTop - clientHeight < 100) {
            if (!this.loadMoreLoading && this.hasMore) {
                this.loadMore();
            }
        }
    }

    // 处理选择模板
    async handleSelectTemplate(templateData: GoodsData["productData"]) {
        Taro.showLoading({ title: '加载中', mask: false });
        designerStore.setLoadding(true);
        designerStore.setDesignData(templateData);
        designerStore.setDesignColor(templateData.color, templateData.colorValue);

        // 2秒自动后隐藏loading
        setTimeout(() => {
            Taro.hideLoading();
        }, 2000);
    }

    // 处理Tab切换
    handleTabChange(index: number) {
        this.activeTabIndex = index;
        // 先设置hasMore为true，确保分页切换时有更多数据可以加载
        this.hasMore = true;
        this.resetPagination();
    }

    // 获取过滤显示的分类
    get visibleCategories() {
        return this.templateCategories.filter(category => category.ifShow !== false);
    }

    // 获取当前激活的分类
    get activeCategory() {
        return this.visibleCategories[this.activeTabIndex];
    }

    // 设置滚动位置
    setScrollTop(scrollTop: number) {
        this.scrollTop = scrollTop;
    }

    // 选择模板
    selectTemplate(categoryId: string, templateId: string) {
        // 这里可以处理模板选择逻辑
    }

    // 跳转到空白页定制
    goToBlankCustomization() {
        // 跳转到定制页面的逻辑
    }

};

const goodsTemlateStore = new GoodsTemlateStore();

export default goodsTemlateStore;